package com.secsbrain.development.web.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpSession;

import com.baomidou.mybatisplus.plugins.Page;
import com.secsbrain.common.ResponseResult;
import com.secsbrain.development.biz.IBranchService;
import com.secsbrain.development.biz.model.BranchParam;
import com.secsbrain.development.dal.mapper.BranchActionRecordMapper;
import com.secsbrain.development.dal.model.BranchActionRecord;
import com.secsbrain.development.dal.model.BranchTypeRule;
import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import springfox.documentation.annotations.ApiIgnore;

@Controller
@RequestMapping("api/branch")
@ApiIgnore
public class BranchController {
	
    private static final Logger logger = LoggerFactory.getLogger(BranchController.class);
    
    @Autowired
    private IBranchService branchService;
    
    @Autowired
    BranchActionRecordMapper branchActionRecordMapper;
    
    /**
     * 功能描述: <br>
     * 查询分支类型
     *
     * @return
     */
    @RequestMapping("type")
    @ResponseBody
    public ResponseResult<List<BranchTypeRule>> type(){
        Map<Long, BranchTypeRule> map=branchService.getBranchTypeCache();
        
        List<BranchTypeRule> list=new ArrayList<>();
        Set<Map.Entry<Long, BranchTypeRule>> entryseSet=map.entrySet();
        for (Map.Entry<Long, BranchTypeRule> entry:entryseSet) {
            if(entry.getValue().getSelected()==1){
                list.add(entry.getValue());
            }
        }
        return new ResponseResult<>(list);
    }
    
    /**
     * 功能描述: <br>
     * 查询分支类型规则
     *
     * @return
     */
    @RequestMapping("type/rule")
    @ResponseBody
    public ResponseResult<List<BranchTypeRule>> typeRule(){
		return branchService.queryBranchTypeRule();
    }
    
    /**
     * 功能描述: <br>
     * 查询分支记录
     *
     * @param start
     * @param limit
     * @param branchActionRecord
     * @return
     */
    @RequestMapping("list")
    @ResponseBody
    public ResponseResult<Page<BranchActionRecord>> list(Integer start, Integer limit, BranchActionRecord branchActionRecord){
        return branchService.queryBranchList(start, limit, branchActionRecord);
    }
    
    /**
     * 功能描述: <br>
     * 查询分支来源
     *
     * @return
     */
    @RequestMapping("sourceBranch")
    @ResponseBody
    public List<String> sourceBranch(Long branchTypeId,Long projectId){
        List<String> resultList=new ArrayList<>();
        Map<Long, BranchTypeRule> map=branchService.getBranchTypeCache();
        if(map.containsKey(branchTypeId)){
            BranchTypeRule branchTypeRule=map.get(branchTypeId);
            String fromIds=branchTypeRule.getBranchFromIds();
            if(fromIds.indexOf(",")!=-1){
                String[] fromIdArray=fromIds.split(",");
                for(String fromId:fromIdArray){
                    resultList.addAll(getBranchName(map,Long.parseLong(fromId),projectId));
                }
            }else{
                resultList.addAll(getBranchName(map,Long.parseLong(fromIds),projectId));
            }
        }
        return resultList;
    }
    
    private List<String> getBranchName(Map<Long, BranchTypeRule> map,Long sourceBranchTypeId,Long projectId){
        List<String> resultList=new ArrayList<>();
        BranchTypeRule sourceBranchTypeRule=map.get(sourceBranchTypeId);
        
        if(projectId==null||projectId==0){
            //不选工程名，目前只可能是develop分支
            resultList.add(sourceBranchTypeRule.getBranchNamePrefix());
            return resultList;
        }
        
        if(sourceBranchTypeRule.getSelected()==0){
            //如果是不可创建分支类型，那么只有一个可选分支
            resultList.add(sourceBranchTypeRule.getBranchNamePrefix());
        }else{
            BranchActionRecord branchActionRecordParam=new BranchActionRecord();
            branchActionRecordParam.setProjectId(projectId);
            branchActionRecordParam.setBranchTypeId(sourceBranchTypeId);
            EntityWrapper<BranchActionRecord> entityWrapper=new EntityWrapper<BranchActionRecord>(branchActionRecordParam);
			List<BranchActionRecord> branchActionRecords=branchActionRecordMapper.selectList(entityWrapper);
            for(BranchActionRecord branchActionRecord:branchActionRecords){
                resultList.add(branchActionRecord.getBranchName());
            }
        }
        return resultList;
    }

    /**
     * 功能描述: <br>
     * 创建分支
     *
     * @return
     */
    @RequestMapping("create")
    @ResponseBody
    public ResponseResult create(BranchParam branchParam, HttpSession session) {
    	//TODO 设置当前用户
//        UserInfoDTO userInfo = (UserInfoDTO) session.getAttribute("userInfo");
//        branchParam.setUserName(userInfo.getLoginName());

        ResponseResult baseResult=branchService.createBranch(branchParam);
        logger.debug("创建分支结果：{}",baseResult);
        return baseResult;
    }
    
}
